<template>
  <div :class="['dashboard-page']" v-loading="pageLoading">
    <div class="dashboard-sider">
      <el-menu
        router
        :default-active="defaultMenu"
        :collapse="isCollapse"
        text-color="#fff"
        active-text-color="white"
        active-background-color="#1973cd"
        background-color="transparent"
        unique-opened
        class="el-menu-vertical-dashboard"
        @open="handleOpen"
        @close="handleClose"
        @select="handleSelect">
        <div class="system-info-block" v-show="!isCollapse">
          <div class="logo">
            <img src="@/assets/images/logo-white.png" alt="logo">
          </div>
          <div class="company">广州天眼科技有限公司</div>
          <div class="system-name">天眼雷达管理系统</div>
        </div>
        <menu-tree :menu="navs" @menuItemClick="handleMenuClick"></menu-tree>
      </el-menu>
    </div>
    <div class="dashboard-right" :style="{ left: isCollapse ? '64px' : '250px' }">
      <div class="dashboard-header">
        <div class="con-btn-group-left">
          <e-icon class="btn" :size="20" :type="isCollapse ? 'Expand' : 'Fold'" @click="collapseSide"></e-icon>
          <e-icon class="btn" :size="20" type="refresh" @click="refresh"></e-icon>
          <div class="breadcrumb-block">
            <el-breadcrumb separator-icon="ArrowRight">
              <el-breadcrumb-item class="breadcrumb-item" v-for="(item, index) in breads" :key="index">
                <span :class="[item.index === route.path ? 'active' : null]" style="line-height: 1.2;">
                  <e-icon v-if="item.icon" class="icon" :type="item.icon"></e-icon>
                  <span>{{item.title}}</span>
                </span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </div>
        <div class="user-info-block">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              <span class="avatar">
                <el-avatar shape="square" :size="30" :src="avatarUrl"/>
              </span>
              <span class="name">{{userInfoStore.userName}}</span>
              <el-icon class="right-icon">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="modify"><e-icon type="Edit"/>修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout"><e-icon type="CloseBold"/>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="con-btn-group btn-right">
          <!-- <span class="btn" style="margin-right: 20px;">
            <el-badge class="warn" :value="warnCount" :max="999" style="line-height: 1;">
              <e-icon type="Bell" :size="20" @click="handleClickWarn"></e-icon>
            </el-badge>
          </span> -->
          <!-- <e-icon class="btn" :size="20" type="FullScreen" @click="handleClickFullscreen"></e-icon> -->
          <span class="btn" style="vertical-align: middle;" @click="handleClickFullscreen">
            <img class="full" style="width: 20px; height: 20px;" :src="isFullscreen ? FSEI : FSI" alt="fullscreen">
          </span>
        </div>
      </div>
      <div class="dashboard-right-block">
        <div class="dashboard-main">
          <!-- <router-view></router-view> -->
          <transition name="fade">
            <router-view v-if="refreshView"></router-view>
          </transition>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <modify-password-form
      :dialogVisible="modifyPwdVis"
      @update:dialogVisible="(value: boolean) => modifyPwdVis = value">
    </modify-password-form>
  </div>
</template>

<script setup lang="ts" name="Dashboard">
import { ref, toRefs, watch, onMounted, nextTick, shallowRef, reactive, onBeforeUnmount, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import EIcon from '@/components/e-icon/e-icon.vue'
import ModifyPasswordForm from './modify-password-form.vue'
import MenuTree from './menu-tree.vue'
import { userInfo } from '@/api/auth'
import navs from '@/config/navs'
import FSI from '@/assets/images/fullscreen.svg'
import FSEI from '@/assets/images/fullscreen-exit.svg'
import screenfull from 'screenfull'
import avatarUrl from '@/assets/images/avatar.png'

const pageLoading = ref(false)
const router = useRouter()
const route = useRoute()
const store = useStore()
// 侧栏相关参数
const defaultMenu = ref()
const activeMenu = ref()
// const menu = ref([])
const { userInfoStore } = toRefs(store.state.user)
const modifyPwdVis = ref(false)
const isCollapse = ref(false)
const isFullscreen = ref(false)
const breads = ref<any>([])
// 生成面包屑
const setBreadcrumb: any = (key: string, nav: any, result: any = []) => {
  for (let i = 0; i < nav.length; i++) {
    let item = nav[i]
    if (item.index === key) {
      return [...result, item]
    } else if (item.children) {
      let found = setBreadcrumb(key, item.children, [...result, item])
      if (found) {
        return found
      }
    }
  }
  return null
}
const warnCount = ref(12)
const refreshView = ref(true)

watch(router.currentRoute, (val) => {
  let arr = setBreadcrumb(val.fullPath, navs)
  breads.value = [...(arr ? arr : [])]
}, {
  immediate: true
})
watch(activeMenu, (newVal) => {
  // console.log(newVal)
})

onMounted(() => {
  defaultMenu.value = router.currentRoute.value.path
  getUserInfo()
  window.addEventListener('keydown', (e: any) => {
    allKey(e)
  })
  window.addEventListener('resize', fullResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('keydown', (e: any) => {})
  window.removeEventListener('resize', fullResize)
})

// resize事件判断全屏
const fullResize = () => {
  isFullscreen.value = screenfull.isFullscreen
}

// 全局键盘事件
const allKey = (e: any) => {
  if (e.keyCode === 122) {
    e.preventDefault()
    handleClickFullscreen()
  }
}

// 告警总数
const handleClickWarn = () => {
}

// 全屏点击事件
const handleClickFullscreen = () => {
  isFullscreen.value = !getFullScreen()
  getFullScreen() ? exitToFullScreen() : turnToFullScreen()
}
const turnToFullScreen = () => {
  if (getFullScreen()) return
  let docElm: any = document.documentElement
  if (docElm.requestFullscreen) {
    docElm.requestFullscreen()
  } else if (docElm.mozRequestFullScreen) {
    docElm.mozRequestFullScreen()
  } else if (docElm.webkitRequestFullScreen) {
    docElm.webkitRequestFullScreen()
  } else if (docElm.msRequestFullscreen) {
    docElm.msRequestFullscreen()
  }
}
const exitToFullScreen = () => {
  if (!getFullScreen()) return
  let docElm: any = document
  if (docElm.exitFullscreen) {
    docElm.exitFullscreen()
  } else if (docElm.mozCancelFullScreen) {
    docElm.mozCancelFullScreen()
  } else if (docElm.webkitCancelFullScreen) {
    docElm.webkitCancelFullScreen()
  } else if (docElm.msExitFullscreen) {
    docElm.msExitFullscreen()
  }
}
const getFullScreen = () => {
  return document.fullscreenElement || (document as any).msFullscreenElement || (document as any).mozFullScreenElement || (document as any).webkitFullscreenElement ? true : false
}

// 切换侧栏伸缩
const collapseSide = () => {
  isCollapse.value = !isCollapse.value
}

// 刷新
const refresh = () => {
  // window.location.reload()
  refreshView.value = false
  setTimeout(() => {
    refreshView.value = true
  }, 500)
}

// 侧栏相关事件
const handleMenuClick = (item: any) => {
}
const handleSelect = (index: number, indexPath: number, item: any) => {
}
const handleOpen = (key: string, keyPath: string[]) => {
  // console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  // console.log(key, keyPath)
}

// 右上角用户栏
const handleCommand = (command: string | number | object) => {
  switch (command) {
    case 'logout':
      ElMessageBox.confirm(
        '确定要退出登录?',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        sessionStorage.removeItem('loginUserInfo')
        router.push({ path: 'login', replace: true })
        // router.replace({ path: 'login'})
      })
      break
    case 'modify':
      modifyPwdVis.value = true
      break
  }
}

// 获取用户信息
const getUserInfo = async () => {
  let sess = sessionStorage.getItem('loginUserInfo')
  let user = JSON.parse(sess!)
  // store.commit('updateUser', { userName: user.userName })
  // console.log(store.state.user.userInfoStore.userId)
  let params = {
    userId: user.userId
  }
  await userInfo(params).then((res: any) => {
    if (res.code === 0) {
      // let sess = sessionStorage.getItem('loginUserInfo')
      // let user = JSON.parse(sess!)
      let info = {
        roleId: res.data.roleId,
        roleName: res.data.roleName,
        userAccount: res.data.userName,
        userId: res.data.id,
        userName: res.data.userAlias
      }
      let obj = Object.assign(user, info)
      sessionStorage.setItem('loginUserInfo', JSON.stringify(obj))
      store.commit('updateUser', { userName: res.data.userAlias, userId: res.data.id })
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error(`接口错误，状态码为 ${err.response.status}。`)
  })
}
</script>

<style lang="stylus" scoped>
.dashboard-page
  height 100%
  width 100%
  position relative
  .dashboard-header
    text-align left
    height 50px
    // margin-bottom 10px
    box-shadow 1px 1px 10px rgba(0, 0, 0, .2)
    position relative
    z-index 2
    .collapse-bar
      margin-left 16px
      margin-top 12px
      cursor pointer
      padding 2px 4px
      background #1370cd
      border-radius 2px
      color white
    .con-btn-group, .con-btn-group-left
      float right
      margin-right 16px
      line-height 50px
      .btn
        width 20px
        height 20px
        display inline-block
        cursor pointer
        vertical-align sub
        transition all .2s linear
        margin-right 16px
        &:hover
          opacity .5
        .full
          vertical-align top
        .warn
          vertical-align top
      .breadcrumb-block
        display inline-block
        vertical-align middle
        .breadcrumb-item
          &:deep(.el-breadcrumb__inner)
            color #888
        .icon
          vertical-align text-bottom
          margin-right 4px
        .active
          font-weight bold
          color #555
    .btn-right
      .btn
        margin-right 0px
    .con-btn-group-left
      float left
      padding 0px 16px
    .user-info-block
      float right
      margin-right 16px
      margin-top 10px
      .warn-count
        display inline-block
        margin-right 30px
        vertical-align bottom
      .el-dropdown-link
        // line-height 60px
        cursor pointer
        .avatar
          vertical-align middle
        .name
          margin 0 10px
        .right-icon
          vertical-align middle
  .dashboard-sider
    position absolute
    height 100%
    // background #1370cd
    background #222c31
    box-shadow 1px 1px 10px rgba(0, 0, 0, .2)
    .el-menu-vertical-dashboard
      height 100%
      // background-image url('@/assets/images/menu-bg.png')
      background-size cover
      background-repeat no-repeat
      &:not(.el-menu--collapse)
        width 250px
      // .el-menu-item
      //   &.is-active
      //     background rgba(0, 0, 0, .2)
      // .el-sub-menu
      //   .el-sub-menu__title
      //     background transparent !important
    .system-info-block
      float left
      width 250px
      line-height 50px
      text-align center
      .logo
        width 100%
        height 80px
        padding 16px
        box-sizing border-box
        padding-bottom 0px
        img
          width 100%
          height 100%
      .company
        color white
        font-size 14px
        line-height 14px
        // margin-bottom 16px
      .system-name
        font-weight bold
        font-size 20px
        color white
  .dashboard-right
    position absolute
    height 100%
    left 250px
    right 0px
    transition left var(--el-transition-duration) ease-in-out
    .dashboard-right-block
      position relative
      height calc(100% - 50px)
      overflow hidden
      .dashboard-main
        position absolute
        // top 51px
        // top 90px
        top 0px
        bottom 0px
        width 100%
        overflow-y auto
        // overflow hidden
        background #efefef
.fade-enter-active, .fade-leave-active
  transition opacity .5s linear
  // position absolute
  // top 0
  // left 0
  overflow hidden
.fade-enter-from, .fade-leave-to
  opacity 0
</style>
<style lang="stylus">
.el-menu--vertical
  &.el-menu--popup-container
    .el-menu-item
      height 40px
      line-height 1
</style>
